//#define DEBUG 1
//#define TARGETXX4 1                     // compile for ATmega164P/324P/664(P)
/*#define PWM10BIT 0 */                     // use 10 bit PWM
#ifndef DMXPWM24_H_
#define DMXPWM24_H_
#define DMX_SIZE 21						 // number of used DMX channels
#define BAUD 250000L					 // DMX512          

#define F_CPU         16000000           // system clock in Hz
#define F_PWM         100L               // PWM frequency in Hz
#define PWM_PRESCALER 8            		 // prescaler for timer 1
#define PWM_CHANNELS  21                 // number of PWM channels

#define PHASE_B      (PIND & (1<<PD2))     // rotary encoder channels
#define PHASE_A      (PIND & (1<<PD3))
#define KEY_PRESSED  (!(PIND & (1<<PD1)))
#define DMX_ADR_CALC 130 //(1+(24*(120>>2))) //((1+(24*(enc_delta>>2))))  // dmx start adress calculation
#define BUILD_NO     44
 

// #ifdef TARGETXX4
// 
//     #define UBRRH UBRR0H
//     #define UBRRL UBRR0L
//     #define TIMSK TIMSK1
//     #define UCSRB UCSR0B
//     #define RXCIE RXCIE0
//     #define RXEN  RXEN0
//     #define USART_RXC_vect USART0_RX_vect
//     #define UCSRA UCSR0A
//     #define UDR   UDR0
//     #define FE    FE0
// 
// #endif

// #ifdef PWM10BIT
//     #define PWM_t uint16_t
//     #define PWM_STEPS     1023              // PWM steps per cylce
// #else
    #define PWM_t uint8_t
    #define PWM_STEPS     255               // PWM steps per cylce
/*#endif*/

// clever bit generator macro

#define PAT(port, bit) ((port==&PORTA) ? (1L<<(bit+24)) : ( \
                        (port==&PORTB) ? (1L<<(bit+16)) : ( \
                        (port==&PORTC) ? (1L<<(bit+8))  : ( \
                        (port==&PORTD) ? (1L<<(bit+0))  : 0))))

// don't change below, will be calculated

#define T_PWM (F_CPU/(PWM_PRESCALER*F_PWM*PWM_STEPS)) // system clocks per PWM clock
//#define T_PWM 1   //TEST

#if ((T_PWM*PWM_PRESCALER)<(160+5))
    #error T_PWM too small, F_CPU must be increased or F_PWM or PWM_STEPS decreased
#endif

#if ((T_PWM*PWM_STEPS)>65535)
	#error period of PWM too big! Increase F_PWM or PWM_PRESCALER !   
#endif

#define UBRR_VAL  ((F_CPU+BAUD*8)/(BAUD*16)-1)  
#define BAUD_REAL (F_CPU/(16*(UBRR_VAL+1)))     
#define BAUD_ERROR ((BAUD_REAL*1000)/BAUD-1000) 
 
#if ((BAUD_ERROR>10) || (BAUD_ERROR<-10))
  #error Systematic baud error above 1% which is too high! 
#endif

typedef struct {
			uint16_t time[PWM_CHANNELS+1];
			uint32_t mask[PWM_CHANNELS+1];
		} pwm_data_t;

// little trick, to speed up data access

typedef union {					
		uint32_t d32;
		uint8_t ary[4];
		} ut_t;

uint8_t  dmx_data[DMX_SIZE];
PWM_t    pwm_data[PWM_CHANNELS];


#endif /* INCFILE1_H_ */